package com.batdream.message.controller;

import com.batdream.message.pojo.Users;
import com.batdream.message.service.ChatService;
import com.batdream.message.service.UserService;
import com.batdream.message.utils.JSONResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author Wang Chen Peng
 * @date 2019/01/03
 * describe: 聊天相关
 */
@Log4j2
@RestController
@RequestMapping("/chat")
public class ChatController {

    private final UserService userService;
    private final ChatService chatService;

    @Autowired
    public ChatController(UserService userService, ChatService chatService) {
        this.userService = userService;
        this.chatService = chatService;
    }

    /**
     * 根据用户id 获取所有未读消息
     * @param myUserId
     * @return
     */
    @PostMapping("/getNoneReadMsgByUserId")
    public JSONResult getNoneReadMsgByUserId(String myUserId) {
        try {
            return JSONResult.ok(chatService.getNoneReadMsgByUserId(myUserId));
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 获取未读消息的最后一条 为了生成聊天快照信息
     *
     * @param myUserId 用户id
     * @return ChatMsg list
     */
    @PostMapping("/getNoneReadChatSnapshot")
    public JSONResult getNoneReadChatSnapshot(String myUserId) {
        try {
            return JSONResult.ok(chatService.getNoneReadChatSnapshot(myUserId));
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }

    private void checkUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            throw new RuntimeException("用户id不能为空");
        }
        Users users = userService.queryUserById(userId);
        if (Objects.isNull(users)) {
            throw new RuntimeException("用户id错误");
        }
    }

}
